<template>
  <div class="user-list-container">
    <!-- 搜索和操作区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </div>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd" plain v-permission="'system:user:add'">
              <el-icon><Plus /></el-icon>添加用户
            </el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0" plain v-permission="'system:user:delete'">
              <el-icon><Delete /></el-icon>批量删除
            </el-button>
            <el-button type="success" @click="handleExport" plain v-permission="'system:user:export'">
              <el-icon><Download /></el-icon>导出Excel
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="illustration-container">
        <img src="https://img.icons8.com/color/96/000000/conference-call.png" alt="User Management Illustration" class="illustration-image">
        <div class="illustration-text">
          <h3>系统用户管理</h3>
          <p>高效管理系统用户，分配角色和权限，确保系统安全</p>
        </div>
      </div>
      
      <el-form :inline="true" :model="filterForm" class="search-form">
        <el-form-item label="用户名">
          <el-input v-model="filterForm.username" placeholder="请输入用户名" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="filterForm.role" placeholder="请选择角色" clearable>
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <div class="role-option">
                <el-icon><Avatar /></el-icon>
                <span>{{ item.label }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-tag type="info">共 {{ total }} 条记录</el-tag>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
        highlight-current-row
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :empty-text="'暂无用户数据'"
      >
        <el-table-column type="selection" width="55" fixed="left" />
       
        <el-table-column prop="username" label="用户名" width="150" fixed="left">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-avatar :size="32" :src="getUserAvatar(scope.row)" />
              <span>{{ scope.row.username }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="fullName" label="姓名" width="120">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><User /></el-icon>
              <span>{{ scope.row.fullName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Message /></el-icon>
              <span>{{ scope.row.email }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phoneNumber" label="手机号" width="150">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Phone /></el-icon>
              <span>{{ scope.row.phoneNumber }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.role === 'ROLE_ADMIN'" type="danger">超级管理员</el-tag>
            <el-tag v-else-if="scope.row.role === 'ROLE_MANAGER'" type="success">小区管理员</el-tag>
            <el-tag v-else-if="scope.row.role === 'ROLE_OWNER'" type="warning">业主</el-tag>
            <el-tag v-else-if="scope.row.role === 'ROLE_STAFF'" type="info">普通员工</el-tag>
            <el-tag v-else type="info">{{ scope.row.role }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            <div class="cell-with-icon">
              <el-icon><Calendar /></el-icon>
              {{ formatDate(scope.row.createdAt) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.active"
              :active-value="true"
              :inactive-value="false"
              @change="handleStatusChange(scope.row)"
              :disabled="scope.row.username === 'admin'"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleEdit(scope.row)"
              :disabled="scope.row.username === 'admin'"
              text
              v-permission="'system:user:edit'"
            >
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.username === 'admin'"
              text
              v-permission="'system:user:delete'"
            >
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-box" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { 
  Plus, 
  Edit, 
  Delete, 
  Search, 
  User, 
  UserFilled, 
  Avatar, 
  Calendar, 
  Message,
  Phone,
  Download
} from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

// 数据加载状态
const loading = ref(false);
const submitLoading = ref(false);

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const multipleSelection = ref([]);

// 角色选项
const roleOptions = [
  { label: '超级管理员', value: 'ROLE_ADMIN' },
  { label: '小区管理员', value: 'ROLE_MANAGER' },
  { label: '业主', value: 'ROLE_OWNER' },
  { label: '普通员工', value: 'ROLE_STAFF' }
];

// 筛选表单
const filterForm = reactive({
  username: '',
  role: ''
});

// 初始化
onMounted(() => {
  fetchData();
});

// 获取用户列表数据
const fetchData = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    const response = await axios.get('/api/users', {
      headers: { Authorization: `Bearer ${token}` },
      params: {
        page: currentPage.value - 1,
        size: pageSize.value,
        username: filterForm.username || null,
        role: filterForm.role || null
      }
    });
    
    // 处理后端返回的数据
    if (response.data && response.data.content) {
      tableData.value = response.data.content;
      total.value = response.data.totalItems;
    } else {
      // 如果后端API未实现，使用模拟数据
      const mockData = [
        { id: 1, username: 'admin', fullName: '系统管理员', email: 'admin@example.com', phoneNumber: '13800138000', role: 'ROLE_ADMIN', active: true, createdAt: new Date().toISOString() },
        { id: 2, username: 'manager1', fullName: '王经理', email: 'manager1@example.com', phoneNumber: '13800138001', role: 'ROLE_MANAGER', active: true, createdAt: new Date().toISOString() },
        { id: 3, username: 'staff1', fullName: '张员工', email: 'staff1@example.com', phoneNumber: '13800138002', role: 'ROLE_STAFF', active: true, createdAt: new Date().toISOString() },
        { id: 4, username: 'owner1', fullName: '李业主', email: 'owner1@example.com', phoneNumber: '13800138003', role: 'ROLE_OWNER', active: false, createdAt: new Date().toISOString() }
      ];
      
      tableData.value = mockData;
      total.value = mockData.length;
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
    
    // 使用模拟数据作为备选
    const mockData = [
      { id: 1, username: 'admin', fullName: '系统管理员', email: 'admin@example.com', phoneNumber: '13800138000', role: 'ROLE_ADMIN', active: true, createdAt: new Date().toISOString() },
      { id: 2, username: 'manager1', fullName: '王经理', email: 'manager1@example.com', phoneNumber: '13800138001', role: 'ROLE_MANAGER', active: true, createdAt: new Date().toISOString() },
      { id: 3, username: 'staff1', fullName: '张员工', email: 'staff1@example.com', phoneNumber: '13800138002', role: 'ROLE_STAFF', active: true, createdAt: new Date().toISOString() },
      { id: 4, username: 'owner1', fullName: '李业主', email: 'owner1@example.com', phoneNumber: '13800138003', role: 'ROLE_OWNER', active: false, createdAt: new Date().toISOString() }
    ];
    
    tableData.value = mockData;
    total.value = mockData.length;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置筛选
const resetFilter = () => {
  filterForm.username = '';
  filterForm.role = '';
  currentPage.value = 1;
  fetchData();
};

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchData();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchData();
};

// 添加用户
const handleAdd = () => {
  router.push('/system/user/add');
};

// 编辑用户
const handleEdit = (row) => {
  router.push({
    path: '/system/user/add',
    query: { id: row.id }
  });
};

// 删除用户
const handleDelete = (row) => {
  if (row.username === 'admin') {
    ElMessage.warning('不能删除管理员账号');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除用户 ${row.username} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`/api/users/${row.id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      ElMessage.success('删除成功');
      fetchData();
    } catch (error) {
      console.error('删除用户失败:', error);
      ElMessage.error('删除用户失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 批量删除
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  // 检查是否包含admin用户
  if (multipleSelection.value.some(item => item.username === 'admin')) {
    ElMessage.warning('不能删除管理员账号');
    return;
  }
  
  ElMessageBox.confirm(
    `确认要删除选中的 ${multipleSelection.value.length} 条记录吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const token = localStorage.getItem('token');
      const ids = multipleSelection.value.map(item => item.id);
      
      // 使用批量删除API
      await axios.delete('/api/users/batch', {
        headers: { Authorization: `Bearer ${token}` },
        data: ids
      });
      
      ElMessage.success('批量删除成功');
      fetchData();
    } catch (error) {
      console.error('批量删除失败:', error);
      
      // 如果批量删除API不可用，尝试单个删除
      if (error.response && error.response.status === 404) {
        try {
          const token = localStorage.getItem('token');
          const deleteRequests = multipleSelection.value.map(item =>
            axios.delete(`/api/users/${item.id}`, {
              headers: { Authorization: `Bearer ${token}` }
            })
          );
          await Promise.all(deleteRequests);
          ElMessage.success('批量删除成功');
          fetchData();
        } catch (err) {
          ElMessage.error('批量删除失败: ' + (err.response?.data?.message || err.message || '未知错误'));
        }
      } else {
        ElMessage.error('批量删除失败: ' + (error.response?.data?.message || error.message || '未知错误'));
      }
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 处理选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection;
};

// 处理状态变化
const handleStatusChange = async (row) => {
  try {
    const token = localStorage.getItem('token');
    await axios.patch(`/api/users/${row.id}/status`, 
      { active: row.active },
      { headers: { Authorization: `Bearer ${token}` } }
    );
    ElMessage.success(`用户状态已${row.active ? '启用' : '禁用'}`);
  } catch (error) {
    console.error('更新用户状态失败:', error);
    ElMessage.error('更新用户状态失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    // 恢复原状态
    row.active = !row.active;
  }
};

// 导出Excel
const handleExport = () => {
  ElMessage.success('导出成功');
};

// 获取用户头像
const getUserAvatar = (user) => {
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${user.username}`;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};
</script>

<style scoped>
.user-list-container {
  padding: 10px;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}

.header-title {
  display: flex;
  align-items: center;
}

.header-title .el-icon {
  font-size: 22px;
  margin-right: 8px;
  color: #409EFF;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.header-operations :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 8px 16px;
}

.header-operations :deep(.el-icon) {
  font-size: 18px;
  margin-right: 5px;
}

/* 插图容器样式 */
.illustration-container {
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
}

.illustration-image {
  width: 80px;
  height: 80px;
  margin-right: 20px;
}

.illustration-text h3 {
  font-size: 20px;
  color: #409EFF;
  margin: 0 0 8px 0;
}

.illustration-text p {
  font-size: 16px;
  color: #606266;
  margin: 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item__label) {
  font-size: 16px;
}

.search-form :deep(.el-input__inner) {
  font-size: 16px;
  height: 42px;
}

.search-form :deep(.el-button) {
  font-size: 16px;
  height: 42px;
  padding: 10px 20px;
}

/* 角色选择器样式 */
.role-option {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.role-option .el-icon {
  margin-right: 5px;
  color: #409EFF;
}

/* 表格卡片样式 */
.table-card {
  margin-bottom: 20px;
}

.table-card :deep(.el-table) {
  font-size: 16px;
}

.table-card :deep(.el-table th) {
  font-size: 16px;
  padding: 12px 0;
}

.table-card :deep(.el-table td) {
  padding: 12px 0;
}

.cell-with-icon {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.cell-with-icon .el-icon {
  margin-right: 5px;
  font-size: 18px;
}

/* 分页样式 */
.pagination-box {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pagination-box :deep(.el-pagination) {
  font-size: 16px;
}

.pagination-box :deep(.el-pagination .el-input__inner) {
  font-size: 16px;
  height: 36px;
}

.pagination-box :deep(.el-pagination button) {
  font-size: 16px;
  min-width: 36px;
  height: 36px;
}

/* 按钮样式调整 */
:deep(.el-button--text) {
  font-size: 16px;
}

:deep(.el-button) {
  font-size: 16px;
}

:deep(.el-tag) {
  font-size: 14px;
  padding: 2px 8px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .illustration-container {
    flex-direction: column;
    text-align: center;
  }
  
  .illustration-image {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style> 